package com.company.bookstore.controller.book_module;


import com.company.bookstore.common.result.MvcResult;
import com.company.bookstore.entities.book_module.Book;
import com.company.bookstore.service.book_module.BookService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 姬深威
 * @since 2020-09-12
 */
@RestController
@Slf4j
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    @PostMapping("/addBooks")
    public MvcResult<Object> addBooks(@RequestBody Book book, BindingResult bindingResult) {
        System.out.println("执行了");
        System.out.println(bindingResult);
//        int bookId = 0;
//        bookId = bookService.addBooks(book);
//        if (bookId == 0) {
//            return MvcResult.UPDATE_FAIL;
//        } else {
//            return MvcResult.UPDATE_SUCCESS;
//        }
        try {
//            int bookId = 0;
            bookService.addBooks(book);
            return MvcResult.UPDATE_SUCCESS;
        } catch (Exception e) {
            return MvcResult.UPDATE_FAIL;
        }
    }

    @PostMapping("/deleteBook/{bookId}")
    public MvcResult<Object> deleteBook(@PathVariable Integer bookId) {
        Integer affectRow = bookService.deleteBook(bookId);
        if (affectRow == 0) {
            return MvcResult.DELETE_FAIL;
        }
        return MvcResult.DELETE_SUCCESS;
    }

    @PostMapping("/handleSelectedBooks/{type}")
    public MvcResult<Object> handleSelectedBooks(@PathVariable Integer type, @RequestBody Integer[] selection) {
        for (Integer i : selection){
            System.out.println(i);
        }
        Integer affectRow = bookService.handleSelectedBooks(type, selection);
        if (affectRow == 0 || affectRow == null) {
            return MvcResult.DELETE_FAIL;
        } else {
            return MvcResult.DELETE_SUCCESS;
        }
    }

    @PostMapping("/updateBook")
    public MvcResult<Object> updateBook(@RequestBody Book book) {
        bookService.updateBook(book);
        return MvcResult.UPDATE_SUCCESS;
    }

    @PostMapping("/handleGrounding")
    public MvcResult<Object> handleGrounding(@RequestBody Book book) {
        Integer affectRow = bookService.handleGrounding(book);
        if (affectRow == 0 || affectRow == null) {
            return MvcResult.UPDATE_FAIL;
        } else {
            return MvcResult.UPDATE_SUCCESS;
        }
    }
}